﻿using AutoMapper;
using DDD.Application;
using DDD.Core;
using DDD.EFCore.Shared;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OrderModule.Domain.OrderAggregate;
using OrderModule.Infrastructure.Repositories;
using OrderModule.IntegrationEvents;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrderModule.Application.Commands
{
    [AutoMapperTo(typeof(Domain.OrderAggregate.Order))]
    public class CreateOrderCommand : ICommand<Domain.OrderAggregate.Order>
    {
        /// <summary>
        /// 订单金额
        /// </summary>
        [Comment("订单金额")]
        [Required]
        [Precision(9, 2)]
        public decimal Amount { get; set; } = 0;


        /// <summary>
        /// 订单项
        /// </summary>
        public List<CreateOrderCommandItem> Items { get; set; } = new List<CreateOrderCommandItem>();
    }

    [AutoMapperTo(typeof(Domain.OrderAggregate.OrderItem))]
    public class CreateOrderCommandItem
    {
        /// <summary>
        /// 商品Id
        /// </summary>
        [Comment("商品Id")]
        [Range(1, int.MaxValue)]
        public int GoodsId { get; set; } = 0;

        /// <summary>
        /// 商品名
        /// </summary>
        [Comment("商品名")]
        [Required]
        [StringLength(20)]
        public string GoodsTitle { get; set; } = string.Empty;

        /// <summary>
        /// 数量
        /// </summary>
        [Comment("数量")]
        [Required]
        public int Quantity { get; set; } = 0;
    }

    public class CreateOrderCommandHandler(IMapper mapper,
        OrderRepository repository,
        DotNetCore.CAP.ICapPublisher publisher,
        ILogger<CreateOrderCommandHandler> logger)
        : ICommandHandler<CreateOrderCommand, Domain.OrderAggregate.Order>
    {
        public async Task<Order> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
        {
            var order = await repository.AddAsync(mapper.Map<Domain.OrderAggregate.Order>(request));
            return order;
        }
    }
}
